package com.k2.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.k2.gulimall.cart.feign.ProductFeignService;
import com.k2.gulimall.cart.interceptor.CartInterceptor;
import com.k2.gulimall.cart.service.CartService;
import com.k2.gulimall.cart.vo.Cart;
import com.k2.gulimall.cart.vo.CartItem;
import com.k2.gulimall.cart.vo.SkuInfoVo;
import com.k2.gulimall.cart.vo.UserInfoTo;
import com.k2.common.utils.R;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    //远程调用的商品
    @Autowired
    private ProductFeignService productFeignService;
    //线程池
    @Autowired
    private ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimiall:cart:";

    @SneakyThrows
    @Override
    public CartItem addToCart(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(res)){
            //购物车内无此商品
            CartItem cartItem = new CartItem();
            //新商品添加入购物车
            CompletableFuture<Void> getStuInFoTask = CompletableFuture.runAsync(() -> {
                //远程查询当前要添加的商品信息
                R skuInfo = productFeignService.info(skuId);
                //System.out.println("111"+skuInfo);
                SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>(){
                });
                cartItem.setCheck(true);
                cartItem.setCount(num);
               // System.out.println("666"+data);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(data.getPrice());
            },executor);

            //远程查询sku的组合信息(需要配置线程池)
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(()->{
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(values);
            });
            CompletableFuture.allOf(getStuInFoTask,getSkuSaleAttrValues).get();
            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), s);
            return cartItem;
        }else {
            //购物车内有此商品
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);

            cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }
    }
    /**
     * 重定向添加成功页面并获取购物车信息
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());
        System.out.println("<-------->"+str);
        CartItem item = JSON.parseObject(str, CartItem.class);
        System.out.println("-------->"+item);
        return item;
    }

    @Override
    /**
     * 查询购物车内商品
     */
    public Cart getCart() {
        Cart cart = new Cart();//存放值
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()!=null){
            //登录购物车
            String cartKey = CART_PREFIX+userInfoTo.getUserId();
            BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
            //如果临时购物车内有数据
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(CART_PREFIX + userInfoTo.getUserKey());
            if (tempCartItems!=null){
                //临时购物车有数据需添加登陆购物车
                for (CartItem item : tempCartItems) {
                    addToCart(item.getSkuId(),item.getCount());
                }
                //清除临时购物车
                clearCart(tempCartKey);
            }
            //获取登陆后的购物车[包含上面合并后的购物车]
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }else{
            //临时购物车
           String cartKey = CART_PREFIX+userInfoTo.getUserKey();
           List<CartItem> cartItems = getCartItems(cartKey);
           cart.setItems(cartItems);

        }
        return cart;
    }

    /**
     * 获取到购物车信息
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //得到用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if(userInfoTo.getUserId()!=null){
            //登录购物车
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        }else{
            //临时购物车
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        //获取购物车信息
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }

    /**
     * 获取临时购物车
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();//拿去所有值
        if (values!=null && values.size()>0) {
            List<CartItem> collect = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }
    public void clearCart(String cartKey){
        redisTemplate.delete(cartKey);
    }

    /**
     * 修改商品是否选中
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);//拿到此商品数据
        cartItem.setCheck(check==1?true:false);//判断是否为true
        String s = JSON.toJSONString(cartItem);//反序列化
        cartOps.put(skuId.toString(),s);//进行存值
    }

    /**
     * 修改商品数量
     * @param skuId
     * @param num
     */
    @Override
    public void countItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    /**
     * 删除购物车商品
     * @param skuId
     */
    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }
}
